package com.giscloud.security.core;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @@author giscloud
 * @Description:
 * @Date: 14:27 2019/5/17
 * @Modified By:
 */
public class CsrfSecurityRequestMatcher implements RequestMatcher {
    private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
    private PathMatcher pathMatcher = null;
    private AntPathRequestMatcher antPathRequestMatcher = null;

    private final List<String> excludePatterns = new ArrayList();
    public  CsrfSecurityRequestMatcher(String httpMethod,String... excludeUrl){
        this.excludePatterns.addAll(Arrays.asList(excludeUrl));
        pathMatcher = new AntPathMatcher();
    }
    @Override
    public boolean matches(HttpServletRequest request) {
        if(allowedMethods.matcher(request.getMethod()).matches()){
            return false;
        }
        String requestPath = getRequestPath(request);
        for (String excludePattern : excludePatterns) {
            return !pathMatcher.match(excludePattern, requestPath);
        }
        return true;
    }
    private String getRequestPath(HttpServletRequest request) {
        String url = request.getServletPath();
        if(request.getPathInfo() != null) {
            url = url + request.getPathInfo();
        }

        return url;
    }
}
